﻿/*
 * listener.hpp
 *
 *  Created on: 2017年2月10日
 *      Author: work
 */

#ifndef _DM_OS_COM_LISTENER_HPP_
#define _DM_OS_COM_LISTENER_HPP_

#include <dm/export.hpp>

#ifndef DM_API_OS_COM
#define DM_API_OS_COM DM_API_IMPORT
#endif

#include <dm/os/com/address.hpp>
#include <dm/os/com/types.hpp>
#include <dm/os/com/device.hpp>

namespace dm{
namespace os{
namespace com{

class DM_API_OS_COM CListener{
	CListener( const CListener& );
	CListener& operator=( const CListener& );

public:
	typedef CDevice device_t;

	enum EState{
		Unlistening = 0,
		Listening
	};

	CListener();
	virtual ~CListener();

	bool setAddress( const CAddress& addr );

	inline const CAddress& getAddress()const{
		return m_addr;
	}

	inline const EState& getState()const{
		return m_state;
	}

	virtual bool startListen();
	virtual bool stopListen();

	inline bool readyForAccept( const size_t& bufSize=1024 ){
		m_connect = startAccept(bufSize);
		return m_connect;
	}

	virtual void handler_connection( const error_t& err );

protected:
	virtual bool checkAndSetAddress( const CTcpServerAddr& addr );
	virtual bool checkAndSetAddress( const CUdpServerAddr& addr );

	virtual void setConnectOnConnect( device_t* connect );
	virtual void onNewConnection( device_t* connect );

	inline void setState( const EState& state ){
		m_state = state;
	}

	virtual bool openPort()=0;
	virtual bool closePort()=0;
	virtual device_t* startAccept(const size_t& bufSize=1024)=0;

protected:
	EState m_state;

	CAddress m_addr;

	device_t* m_connect;
};

}
}
}


#endif /* INCLUDE_DM_OS_COM_LISTENER_HPP_ */
